
#用类的方法 来构造一个通用的适用于zabbix监控的方法



# ---------------------------------------------------------------------------------------------------------
#导入模块
import sys
import json
import requests


class ZabbixAPI():

    #构造传值变量方法
    def __init__(self,api,user,password):
        self.api = api
        self.user = user
        self.password = password

    #发送API获取数据
    def sendPost(self,data):

        head = {"Content-Type":"application/json"}

        try:
            res = requests.post(url=self.api,data=json.dumps(data),headers=head)
        except Exception as e:
            print("zabbix-API 请求调用失败")
            print(e)
            sys.exit()

        return json.loads(res.text)

    #获取令牌
    #__ 代表是一个私有方法，确保数据的安全性，不会在创建过程中显示
    def __Get_API_token(self):

        data = {
           "jsonrpc": "2.0",
           "method": "user.login",
           "params": {
               "user": self.user,
               "password": self.password
           },
           "id": 1
        }

        res = self.sendPost(data=data)
        use_token = res.get("result")
        return use_token

    #获取模板ID
    def GET_templateID(self):

        token = self.__Get_API_token()
        data={
           "jsonrpc": "2.0",
           "method": "template.get",
           "params": {
               "output": "extend",
               "filter": {
                   "host": [
                       "Template OS Linux by Zabbix agent",
                   ]
               }
           },
           "auth": token,
           "id": 1
        }

        res = self.sendPost(data=data)
        template_id = res.get("result")[0].get("templateid")
        return template_id

    #获取主机组ID 如果有直接获取，没有就创建
    def GET_host_id(self):
        token = self.__Get_API_token()

        all_group_data = {
           "jsonrpc": "2.0",
           "method": "hostgroup.get",
           "params": {
               "output": "extend",
           },
           "auth": token,
           "id": 1
        }

        src = self.sendPost(data=all_group_data)

        #把所有的主机名称与ID放入另一个字典
        new_group_item = []
        for info in src.get("result"):
            new_group_item[info.get("name")] = info.get("groupid")

        if host_group_name in new_group_item:
            host_group_id = all_group_data.get(host_group_name)
            return host_group_id
        else:
            create_group_host_data = {
               "jsonrpc": "2.0",
               "method": "hostgroup.create",
               "params": {
                   "name": host_group_name
               },
               "auth": token,
               "id": 1
            }
            res = self.sendPost(data=create_group_host_data)
            host_group_id = res.get("result").get("groupids")[0]
            return host_group_id


    def Create_new_host(self,host_ip, host_name, host_group_name):
        token = self.__Get_API_token()
        tempfileid = self.GET_templateID()
        hostgroupid = self.GET_host_id(host_group_name=host_group_name)

        data = {
           "jsonrpc": "2.0",
           "method": "host.create",
           "params": {
               "host": host_name,
               "interfaces": [
                   {
                       "type": 1,
                       "main": 1,
                       "useip": 1,
                       "ip": host_ip,
                       "dns": "",
                       "port": "10050"
                   }
               ],
               "groups": [
                   {
                       "groupid": hostgroupid
                   }
               ],
               "templates": [
                   {
                       "templateid": tempfileid
                   }
               ],
           },
           "auth": token,
           "id": 1
        }

        res = self.sendPost(data=data)
        if "error" in res:
            print("【%s】创建主机失败" %host_ip)
        else:
            print("创建主机成功" %host_ip)



if __name__ == '__main__':
    hostname = input("被监控机名称：").strip()
    hostip = input("被监控机地址：").strip()
    hostgroup = input("要添加或创建的主机组：").strip()

    p1 = ZabbixAPI(api="http://192.168.106.133/zabbix/api_jsonrpc.php",user="Admin",password="zabbix")
    p2 = p1.Create_new_host(host_ip=hostip,host_name=hostname,host_group_name=hostgroup)


